import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;

import org.apache.mina.core.RuntimeIoException;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.example.sumup.ClientSessionHandler;
import org.apache.mina.example.sumup.codec.SumUpProtocolCodecFactory;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.nio.NioSocketConnector;


public class MinaClient {

	private static final long CONNECT_TIMEOUT = 1000;
	private static final boolean USE_CUSTOM_CODEC = false;
	private static InetAddress HOSTNAME;
	private static final int PORT = 1234;

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			HOSTNAME = InetAddress.getLocalHost();
		} catch (UnknownHostException e1) {
			e1.printStackTrace();
		}
	    NioSocketConnector connector = new NioSocketConnector();

	    // Configure the service.
	    connector.setConnectTimeoutMillis(CONNECT_TIMEOUT);
	    if (USE_CUSTOM_CODEC) {
	       connector.getFilterChain().addLast("codec",
	                                         new ProtocolCodecFilter(new SumUpProtocolCodecFactory(false)));
	    } else {
	       connector.getFilterChain().addLast("codec",
	                                         new ProtocolCodecFilter(new ObjectSerializationCodecFactory()));
	    }
	    connector.getFilterChain().addLast("logger", new LoggingFilter());
	    connector.setHandler(new ClientSessionHandler(new int[] { 1 }));

	    IoSession session;
	    for (;;) {
	        try {
				ConnectFuture future = connector.connect(new InetSocketAddress(HOSTNAME, PORT));
	            System.out.println("CONNECTED!");
				future.awaitUninterruptibly();
	            session = future.getSession();
	            break;
	        } catch (RuntimeIoException e) {
	            System.err.println("Failed to connect.");
	            e.printStackTrace();
	            try {
					Thread.sleep(5000);
				} catch (InterruptedException e1) {
					e1.printStackTrace();
				}
	        }
	    }

	    // wait until the summation is done
	    session.getCloseFuture().awaitUninterruptibly();
	    connector.dispose();
	}
}
